﻿@model QueuedEmailListModel
@using Telerik.Web.Mvc.UI
@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    //page title
    ViewBag.Title = T("Admin.System.QueuedEmails").Text;
}
@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-system.png")" alt="" />
            @T("Admin.System.QueuedEmails")
        </div>
        <div class="options">
            <input type="button" id="delete-selected" class="t-button" value="@T("Admin.System.QueuedEmails.DeleteSelected")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchStartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchStartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchEndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchEndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchFromEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchFromEmail)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchToEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchToEmail)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchLoadNotSent):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchLoadNotSent)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchMaxSentTries):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.SearchMaxSentTries)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToNumber)
                <input type="submit" name="go-to-email-by-number" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<QueuedEmailModel>()
                        .Name("queuedEmails-grid")
                .ClientEvents(events => events.OnDataBinding("onDataBinding").OnDataBound("onDataBound"))
                        .Columns(columns =>
                        {
                            columns.Bound(x => x.Id)
                            .ClientTemplate("<input type='checkbox' value='<#= Id #>' class='checkboxGroups'/>")
                            .Title("<input id='mastercheckbox' type='checkbox'/>")
                            .Width(50)
                            .HtmlAttributes(new { style = "text-align:center" })
                            .HeaderHtmlAttributes(new { style = "text-align:center" });

                            columns.Bound(x => x.Id).Width(50);
                            columns.Bound(x => x.Subject).Width(300);
                            columns.Bound(x => x.From).Width(100);
                            columns.Bound(x => x.To).Width(100);
                            columns.Bound(x => x.CreatedOn).Width(100);
                            columns.Bound(x => x.SentOn).Width(150);
                            columns.Bound(x => x.Priority).Width(50);
                            columns.Bound(x => x.Id)
                                .Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
                                .ClientTemplate("<a href=\"Edit/<#= Id #>\">" + T("Admin.Common.Edit").Text + "</a>")
                                .Width(50)
                                .Centered()
                                .HeaderTemplate(T("Admin.Common.Edit").Text)
                                .Filterable(false);
                        })
                        .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                        .DataBinding(dataBinding => dataBinding.Ajax().Select("QueuedEmailList", "QueuedEmail"))
                        .EnableCustomBinding(true))
            </td>
        </tr>
    </table>
    
    <script type="text/javascript">
        var selectedIds = [];

        $(document).ready(function () {

            //search button
            $('#btnSearch').click(function () {
                //search
                var grid = $('#queuedEmails-grid').data('tGrid');
                grid.currentPage = 1; //new search. Set page size to 1
                grid.ajaxRequest();
                //clear selected checkboxes
                $('.checkboxGroups').attr('checked', false).change();
                selectedIds = [];
                return false;
            });

            $("#@Html.FieldIdFor(model => model.SearchFromEmail)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#btnSearch").click();
                    return false;
                }
            });

            $("#@Html.FieldIdFor(model => model.SearchToEmail)").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#btnSearch").click();
                    return false;
                }
            });
            
            //"delete selected" button
            $('#delete-selected').click(function (e) {
                e.preventDefault();

                var postData = {
                    selectedIds: selectedIds
                };

                $.ajax({
                    cache:false,
                    type: "POST",
                    url: "@(Url.Action("DeleteSelected", "QueuedEmail"))",
                    data: postData,
                    complete: function (data) {
                        //reload grid
                        var grid = $('#queuedEmails-grid').data('tGrid');
                        grid.currentPage = 1; //new search. Set page size to 1
                        grid.ajaxRequest();
                        //clear selected checkboxes
                        $('.checkboxGroups').attr('checked', false).change();
                        selectedIds = [];
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert(thrownError);
                    },
                    traditional: true
                });
                return false;
            });
            
            $('#mastercheckbox').click(function () {
                $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
            });

            //wire up checkboxes. 
            $('#queuedEmails-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                var $check = $(this);
                if ($check.is(":checked") == true) {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked == -1) {
                        //add id to selectedIds.  
                        selectedIds.push($check.val());
                    }
                }
                else {
                    var checked = jQuery.inArray($check.val(), selectedIds);
                    if (checked > -1) {
                        //remove id from selectedIds.  
                        selectedIds = $.grep(selectedIds, function (item, index) {
                            return item != $check.val();
                        });
                    }
                }
                updateMasterCheckbox();
            });
        });

    function onDataBinding(e) {
        var searchModel = {
                SearchStartDate: $('#@Html.FieldIdFor(model => model.SearchStartDate)').val(),
                SearchEndDate: $('#@Html.FieldIdFor(model => model.SearchEndDate)').val(),
                SearchFromEmail: $('#@Html.FieldIdFor(model => model.SearchFromEmail)').val(),
                SearchToEmail: $('#@Html.FieldIdFor(model => model.SearchToEmail)').val(),
                SearchLoadNotSent: $('#@Html.FieldIdFor(model => model.SearchLoadNotSent)').is(':checked'),
                SearchMaxSentTries: $('#@Html.FieldIdFor(model => model.SearchMaxSentTries)').val()
                };
        e.data = searchModel;
    }

    function onDataBound(e) {

        $('#queuedEmails-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
            var currentId = $(this).val();
            var checked = jQuery.inArray(currentId, selectedIds);
            //set checked based on if current checkbox's value is in selectedIds.  
            $(this).attr('checked', checked > -1);
        });

        updateMasterCheckbox();
    }
    
    function updateMasterCheckbox() {
        var numChkBoxes = $('#queuedEmails-grid input[type=checkbox][id!=mastercheckbox]').length;
        var numChkBoxesChecked = $('#queuedEmails-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }
    </script>
    
}